<?php
/**
 * Dirox Framework
 * Copyright (C) 2005 - 2007 Dirox / Synexser
 * 
 * All rights reserved.
 */

if (defined("SESSION_HANDLER_TYPE") && SESSION_HANDLER_TYPE === "DATABASE") {
	require_once(APPLICATION_DIR."/application/model/Sessions.php");
}

class DRX_SessionHandler
{
	var $_session_db;

	function open()
	{
		$this->_session_db = new DataObjects_Sessions();
	    return $this->_session_db;
	}

    function close()
    {
    	return true;
    }

    function read($id)
    {
    	$this->_session_db->id = $id;
	    $this->_session_db->selectAdd();
	    $this->_session_db->selectAdd("data");
		$this->_session_db->find(true);

		return $this->_session_db->data;
    }

    function write($id, $data)
    {
		$access = time();

	    $id = mysql_real_escape_string($id);
	    $access = mysql_real_escape_string($access);
	    $data = mysql_real_escape_string($data);

	    $res = $this->_session_db->query(
	    	"REPLACE
            INTO    SESSIONS
            VALUES  ('$id', '$access', '$data')"
	    );

	    return ($res !== DB_Error) ? true : false;
    }

    function destroy($id)
    {
    	$this->_session_db->id = $id;
	    return $this->_session_db->delete();
    }

    function gc($maxlifetime)
    {
    	$old = time() - $maxlifetime;
	    $old = mysql_real_escape_string($old);

	    $this->_session_db->whereAdd("access < '$old'");
	    return $this->_session_db->delete(true);
	}
	
	function remove($varname)
	{
		unset($_SESSION[$varname]);
	}

	function set($varname, $value = '')
	{
		$_SESSION[$varname] = $value;
	}

	function get($varname)
	{
		return isset($_SESSION[$varname]) ? $_SESSION[$varname] : '';
	}

	function getNumber($varname)
	{
		$str_value = Session::get($varname);
		return is_numeric($str_value) ? $str_value : 0;
	}

	function getIntNumber($varname)
	{
		return intval(Session::getNumber($varname));
	}
	
	function exist($varname)
	{
		return isset($_SESSION[$varname]);
	}
}

?>
